package com.me.springsimple.security.provider;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.BadCredentialsException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.me.springsimple.entity.EmpEntity;
import com.me.springsimple.security.service.SecurityService;
import com.me.springsimple.security.user.SpringsimpleUser;

@Service
public class DaoUserDetails implements UserDetailsService{

	@Autowired
	private SecurityService securityService;
	
	private static final Logger LOGGER = Logger.getLogger(DaoUserDetails.class);
			
	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {

		boolean enabled = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;
		LOGGER.info("Step UserDetails");
		GrantedAuthority[] authorities = {new GrantedAuthorityImpl("ROLE_USER")};
		if(username.equals("") || username == null){
			throw new BadCredentialsException("Wrong username or password");
		}else{
			
			List<EmpEntity> user = securityService.findUser(username);
			if (user.size() == 0){
				throw new BadCredentialsException("Wrong username or password");
			}
			
			EmpEntity emp = (EmpEntity) user.get(0);
			
			return new SpringsimpleUser(emp.getUsername(),emp.getPassword(),enabled,accountNonExpired,credentialsNonExpired,accountNonLocked,authorities,emp.getName(),emp.getLname(),emp.getAge().toString());
			
		}
	}

}
